package atom.core0.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;

import org.apache.log4j.Logger;

import atom.core0.exception.BizSysException;

public class BlobUtil {
	private Logger logger = Logger.getLogger(BlobUtil.class);
	public static void blobToFile(Blob blob, String filename) throws BizSysException
	{
		if (blob==null)
			throw new BizSysException("Blob参数是空");		
		try
		{
			File file = new File(filename);
			InputStream ins = blob.getBinaryStream();
			FileOutputStream fout = new FileOutputStream(file);
			byte[] b = new byte[1024];

			int len = 0;

			while ((len = ins.read(b)) != -1)
			{

				fout.write(b, 0, len);

			}
			fout.close();
			ins.close();

		}
		catch (Exception e)
		{
			throw new BizSysException("保存Blob对象到文件[" + filename + "]失败");
		}
		// 
	}
	public static byte[] blobToByte(Blob blob) throws BizSysException
	{
		if (blob==null)
			throw new BizSysException("Blob参数是空");		
		try
		{
			InputStream ins = blob.getBinaryStream();
			/*
			byte[] b=null;
			int size = ins.available();
			if (size<=0)
				return b;
			else if (size>1024*1024*10)
				throw new BizException("blob字段转成byte数字超过10M,拒绝");
			b = new byte[size];

			ins.read(b, 0, size);
			ins.close();
			
			return b;
			*/
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = ins.read(b, 0, b.length)) != -1)
			{
				baos.write(b, 0, len);
			}
			byte[] buffer = baos.toByteArray();
			baos.close();

			return buffer;
			

		}
		catch (Exception e)
		{
			throw new BizSysException("保存Blob对象到byte数组失败");
		}

	}

}
